package org.travel_system.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.travel_system.pojo.Restaurant;
import org.travel_system.utils.Result;
import org.travel_system.service.RestaurantService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RestController
@RequestMapping("/restaurants")
public class RestaurantController {

    private final RestaurantService restaurantService;

    @Autowired
    public RestaurantController(RestaurantService restaurantService){this.restaurantService = restaurantService;}

    //获取餐馆列表
    @GetMapping
    public Result<List<Restaurant>> getAllRestaurants() {
        return Result.success(restaurantService.getRestaurants());
    }

    //获得餐馆的封面
    @GetMapping("/images")
    public Result<List<Map<String, String>>> getAllRestaurantsImages() {
        List<Restaurant> restaurants = restaurantService.getRestaurants();

        // 使用Stream API将每个餐馆对象转换为一个包含 image 属性的Map
        List<Map<String, String>> images = restaurants.stream()
                .map(restaurant -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("url", restaurant.getPhoto());  // 添加餐馆图像URL
                    return map;
                })
                .collect(Collectors.toList());
        return Result.success(images);
    }
    //获取餐馆信息通过名字
    @GetMapping("/{name}")
    public Result<Restaurant> getRestaurantByName(@PathVariable String name){
        return Result.success(restaurantService.getRestaurantByName(name));
    }

    //模糊搜索餐厅名字
    @GetMapping("/search/{name}")
    public Result<List<Restaurant>> getSearchRestaurantByName(@PathVariable String name){
        return Result.success(restaurantService.getSearchRestaurantByName(name));
    }


    //添加餐馆
    @PostMapping
    public Result<?> addRestaurant(@RequestBody Restaurant restaurant){
        return restaurantService.addRestaurant(restaurant) > 0 ?
                Result.success() :
                Result.error("添加餐馆失败");
    }

    //删除餐馆
    @DeleteMapping
    public Result<?> deleteRestaurant(@RequestParam String name){
        return restaurantService.deleteRestaurantByName(name) > 0 ?
                Result.success() :
                Result.error("删除餐馆失败");
    }

    //修改餐馆
    @PutMapping
    public Result<?> updateRestaurant(@RequestBody Restaurant restaurant){
        return restaurantService.updateRestaurant(restaurant) > 0 ?
                Result.success() :
                Result.error("修改餐馆失败");
    }
}
